import {AfterViewInit, Directive, ElementRef, HostListener, Inject, OnInit} from '@angular/core';
import {DOCUMENT} from '@angular/common';

@Directive({
    selector: '[appScrollHold]'
})
export class ScrollHoldDirective implements AfterViewInit {
    top = 96;
    winHeight: number;
    width: number;

    offsetTop: number;

    constructor(private element: ElementRef,
                @Inject(DOCUMENT) private document: Document) {
    }

    ngAfterViewInit(): void {
        const el = this.document.scrollingElement || this.document.documentElement;
        this.winHeight = window.innerHeight;
        this.width = this.element.nativeElement.getBoundingClientRect().width;
        this.offsetTop = this.element.nativeElement.getBoundingClientRect().top + el.scrollTop;
        this.element.nativeElement.style.position = 'fixed';
        this.element.nativeElement.style.width = this.width + 'px';
        this.element.nativeElement.style.top = this.offsetTop + 'px';
        this.resize();
    }

    @HostListener('window:resize', ['$event'])
    onResize(event) {
        this.resize();
        this.onWindowScroll(null);
    }

    @HostListener('window:scroll', ['$event'])
    onWindowScroll(event) {
        const el = this.document.scrollingElement || this.document.documentElement;
        const scrollTop = el.scrollTop;
        let top;
        let height;
        if (scrollTop < this.offsetTop) {
            top = (this.offsetTop - scrollTop);
            height = (this.winHeight - this.offsetTop + scrollTop + 2);
        } else {
            top = 0;
            height = this.winHeight;
        }
        this.element.nativeElement.style.top = top + 'px';
        this.element.nativeElement.style.height = height + 'px';
    }

    resize() {
        const height = this.element.nativeElement.height;
        this.winHeight = window.innerHeight;

        this.element.nativeElement.style.height = (this.winHeight - this.offsetTop) + 'px';
    }
}
